<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>WiFi Config</title>
  <link rel="stylesheet" href="/tailwind.min.css">
  <link rel="stylesheet" href="/tailwind-simple-form.css">
  <link rel="stylesheet" href="/style.css">
</head>
<body class="bg-gray-100 p-6">
  <div class="max-w-3xl mx-auto">
    <h1 class="text-2xl font-bold mb-4">WiFi 配置</h1>
    <form id="wifiForm" class="simple-form">
      <label>SSID
        <input type="text" name="ssid" id="ssid" placeholder="SSID" />
      </label>
      <label>密码
        <input type="password" name="password" id="password" placeholder="Password" />
      </label>
      <div>
        <button type="submit">保存并连接</button>
      </div>
    </form>

    <h2 class="text-xl font-semibold mt-8">RSSI 变化 (每10秒更新)</h2>
    <canvas id="rssiChart" width="600" height="300"></canvas>
  </div>

  <script src="/chart.min.js"></script>
  <script>
    const ctx = document.getElementById('rssiChart').getContext('2d');
    const data = { labels: [], datasets: [{ label: 'RSSI (dBm)', data: [], borderColor: 'rgb(75, 192, 192)', tension: 0.1 }] };
    const config = { type: 'line', data };
    const rssiChart = new Chart(ctx, config);

    let ws;
    function startWS() {
      ws = new WebSocket(`ws://${location.host}/ws`);
      ws.onopen = () => console.log('ws open');
      ws.onmessage = (evt) => {
        try { const obj = JSON.parse(evt.data); const time = new Date().toLocaleTimeString(); data.labels.push(time); data.datasets[0].data.push(obj.rssi); if (data.labels.length > 20) { data.labels.shift(); data.datasets[0].data.shift(); } rssiChart.update(); } catch(e) { console.error(e); }
      };
      ws.onclose = () => setTimeout(startWS, 2000);
    }
    startWS();

    document.getElementById('wifiForm').addEventListener('submit', async (e) => {
      e.preventDefault();
      const ssid = document.getElementById('ssid').value;
      const password = document.getElementById('password').value;
      const resp = await fetch('/configure', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ ssid, password }) });
      const j = await resp.json();
      alert('保存: ' + j.status);
    });
  </script>
</body>
</html>
